package com.feixiang.springbootinit.strategy;
import cn.hutool.json.JSONUtil;
import com.feixiang.springbootinit.common.ErrorCode;
import com.feixiang.springbootinit.exception.BusinessException;
import com.feixiang.springbootinit.model.entity.wechat.QwMessage;
import com.feixiang.springbootinit.model.entity.wechat.QwVoiceMessage;
import com.feixiang.springbootinit.model.enums.SessionArchiveMsgTypeEnum;
import com.feixiang.springbootinit.model.vo.wechat.MsgVO;
import com.feixiang.springbootinit.processor.SessionArchiveBatchProcessor;
import com.feixiang.springbootinit.processor.SessionArchiveProcessor;
import com.feixiang.springbootinit.service.FileStorageService;
import com.feixiang.springbootinit.service.QwVoiceMessageService;
import com.feixiang.springbootinit.utils.BatchSaveUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class VoiceMessageStrategy implements MessageProcessingStrategy {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private QwVoiceMessageService voiceMessageService;

    @Override
    public boolean supports(SessionArchiveMsgTypeEnum msgType) {
        return SessionArchiveMsgTypeEnum.VOICE == msgType;
    }

    @Override
    public void process(MsgVO msgVO, QwMessage baseMessage) {
        try {
            // 获取当前线程的SDK实例（从ThreadLocal中）,媒体资源需要拉取
            //long sdk = SessionArchiveUtil.getSDK();
            // 直接使用全局SDK实例（需确保线程安全）
            long sdk = SessionArchiveProcessor.getGlobalSdkInstance();
            // 调用文件存储服务
            log.info("处理语音消息");
            log.info("存储语音文件: {}", msgVO.getVoice().getSdkfileid());
            String storedPath = fileStorageService.storeFile(
                    sdk,
                    msgVO.getVoice().getSdkfileid(),
                    msgVO.getVoice().getMd5sum(),
                    "amr", //扩展名,微信语音消息是amr
                    "voice" // 子目录
            );
            // 获取访问URL并保存到数据库
            String mediaUrl = fileStorageService.getFileUrl(storedPath);
            QwVoiceMessage voiceMessage = new QwVoiceMessage();
            voiceMessage.setMsgId(msgVO.getMsgid());
            voiceMessage.setMediaUrl(mediaUrl);
            voiceMessage.setVoiceSize(msgVO.getVoice().getVoice_size());
            voiceMessage.setPlayLength(msgVO.getVoice().getPlay_length());
            voiceMessage.setCreatedTime(new Date());
            voiceMessageService.save(voiceMessage);

        } catch (Exception e) {
            log.error("处理语音消息失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "处理语音消息失败");
        }
    }

    /**
     * 批量处理语音消息
     *
     * @param baseMessages
     */
    @Override
    public void batchProcess(List<QwMessage> baseMessages) {
        if (baseMessages.isEmpty()) {
            log.info("批量处理语音消息: 空列表，无需处理");
            return;
        }
        log.info("开始批量处理语音消息，数量: {}", baseMessages.size());
        long sdk = SessionArchiveBatchProcessor.getGlobalSdkInstance();
        List<QwVoiceMessage> voiceMessages = new ArrayList<>(baseMessages.size());
        Date currentTime = new Date();
        for (QwMessage baseMsg : baseMessages) {
            try {
                // 从基础消息中解析出原始消息对象
                MsgVO msgVO = JSONUtil.toBean(baseMsg.getContent(), MsgVO.class);
                if (msgVO.getVoice() == null) {
                    log.warn("语音消息内容为空，msgId: {}", baseMsg.getMsgId());
                    continue;
                }
                // 存储文件
                String storedPath = fileStorageService.storeFile(
                        sdk,
                        msgVO.getVoice().getSdkfileid(),
                        msgVO.getVoice().getMd5sum(),
                        "amr",
                        "voice"
                );
                // 构建语音消息实体
                QwVoiceMessage voiceMsg = new QwVoiceMessage();
                voiceMsg.setMsgId(msgVO.getMsgid());
                voiceMsg.setMediaUrl(fileStorageService.getFileUrl(storedPath));
                voiceMsg.setVoiceSize(msgVO.getVoice().getVoice_size());
                voiceMsg.setPlayLength(msgVO.getVoice().getPlay_length());
                voiceMsg.setCreatedTime(currentTime);
                voiceMessages.add(voiceMsg);
            } catch (Exception e) {
                log.error("批量处理单条语音消息失败, msgId: {}", baseMsg.getMsgId(), e);
                // 单条失败不影响整体批次，继续处理其他消息
            }
        }
        // 批量保存到数据库
        BatchSaveUtil.batchSave(voiceMessages,voiceMessageService::insertBatch,"语音消息");
//        if (!voiceMessages.isEmpty()) {
//            try {
//                // 分批次保存，每批最多500条
//                int batchSize = 500;
//                for (int i = 0; i < voiceMessages.size(); i += batchSize) {
//                    int end = Math.min(i + batchSize, voiceMessages.size());
//                    List<QwVoiceMessage> subList = voiceMessages.subList(i, end);
//                    voiceMessageService.saveBatch(subList);
//                    log.info("已保存语音消息批次: {}-{}, 数量: {}", i, end - 1, subList.size());
//                }
//                log.info("批量处理语音消息完成，成功保存: {}", voiceMessages.size());
//            } catch (Exception e) {
//                log.error("批量保存语音消息失败", e);
//                throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量保存语音消息失败");
//            }
//        } else {
//            log.info("批量处理语音消息完成，无有效消息可保存");
//        }

    }
}